import { defineStore } from "pinia";
import router from "@/router";
import { ElMessage } from "element-plus";
import { login as loginApi } from "@/api/login";

export const useLoginStore = defineStore("login", {
  state: () => ({
    count: 0, // 计数器
    loginData: { adminName: "", password: "" }, // 登录数据，包括管理员名和密码
    token: localStorage.getItem("token") || "", // 从localStorage获取的token，默认为空字符串
    siderType: true, // 侧边栏类型，默认为true
    lang: localStorage.getItem("lang") || "zh", // 语言设置，默认为中文
  }),
  getters: {
    // 判断是否登录，根据token是否为空字符串来判断
    isLogin: (state) => {
      return state.token !== "";
    },
    // 获取当前语言设置
    getLang: (state) => {
      return state.lang;
    },
    // 获取当前token
    getToken: (state) => {
      return state.token;
    },
  },
  actions: {
    // 异步登录方法，接受一个value参数，用于设置登录数据并发送登录请求
    async asyncLogin(value) {
      this.loginData = value;

      try {
        const res = await loginApi(value);
        this.token = res.data;
        localStorage.setItem("token", res.data);
        ElMessage.success("登录成功");
        router.push("/");
      } catch (error) {
        console.error("Login failed:", error);
        ElMessage.error("登录失败，请检查用户名和密码");
      }
    },

    // 登出方法，清除localStorage中的token并重置state中的token
    logout() {
      localStorage.clear();
      this.token = "";
      router.replace("/login");
    },
  },
});
